﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HANS_BackStage.Common;
using HANS.Utility.Extensions;
using HANS_BackStage.Impl;
using HANS_BackStage.Model.DbModel;
using HANS_BackStage.Model.WebModel;
using WebApplication1;

namespace HANS_BackStageWeb.Common
{
    public class BackStagAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            HANS_BackStage.Common.FormsAuthenticationHelper.RenewCurrentUser();
            if (!base.AuthorizeCore(httpContext))
            {
                return false;
            }
            else
            {
                var login_Info = HttpContext.Current.Session[SessionConstant.ADMININFO_KEY] as HANS_BackStage.Model.WebModel.Login_AdminInfo;
                if (login_Info.IsNull())
                {
                    var login_mark = httpContext.User?.Identity?.Name;//存放规则：Name.Role_type
                    string[] marks = login_mark.Split(',');
                    var admin = AdminServices.GetByName(marks[0]);
                    if (admin == null)
                    {
                        return false;

                    }

                    List<Backstage_role> roles = new List<Backstage_role>();
                    List<Perissions> permissionsList = new List<Perissions>();
                    roles = Role_PermiServices.GetRoles(Role_PermiServices.GetRoles(admin.Id));
                    if (roles.Find(r => r.Id.Equals(marks[1])) != null)
                    {
                        foreach (var item in roles)
                        {
                            Perissions per = new Perissions(item)
                            {
                                permissions = Role_PermiServices.GetPermissions(Role_PermiServices.GetPermissions(item.Id)),
                            };
                            permissionsList.Add(per);
                        }
                        Login_AdminInfo loginInfo = new Login_AdminInfo(admin, roles, permissionsList, marks[1]);
                    }
                }
                if (login_Info.IsNotNull())
                {
                    var AllPermissions = Role_PermiServices.GetAllPermissions();
                    //当前请求的controller和action
                    var controller = httpContext.Request.RequestContext.RouteData.Values["controller"].AsString();
                    var action = httpContext.Request.RequestContext.RouteData.Values["action"].AsString();
                    var url = httpContext.Request.Url?.AbsolutePath;

                    //在所有权限寻找最精确的权限
                    var permission = AllPermissions.FirstOrDefault(p => p.Url == url);
                    if (permission.IsNull())
                    {
                        permission = AllPermissions.FirstOrDefault(p => p.Controller.EqualsNoCase(controller) && p.Action.EqualsNoCase(action));
                    }
                    if (permission.IsNull())
                    {
                        permission = AllPermissions.FirstOrDefault(p => p.Controller.EqualsNoCase(controller) && (p.Action == null || p.Action == ""));
                    }
                    //如果还没有，说明该链接不需要特殊权限，直接允许；如果有，就判断用户是否有此权限
                    return permission.IsNull() || login_Info.NowPermission.Count(p => permission.Id == p.Id) > 0;
                }
                else
                {
                    return false;
                }
            }
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult()
                {
                    Data = new { }//ajax授权失败
                };
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(RouteConfig.BackStageDefault,
                    RouteValuesHelper.From(
                        new
                        {
                            controller = "Home",
                            action = "Login",
                            returnUrl = filterContext.RequestContext.HttpContext.Request.RawUrl
                        })
                );
            }
        }
    }
}